package com.closer.service.support.aop;

import com.closer.service.biz.user.dto.vo.LoginUserVO;
import com.closer.service.biz.user.enums.UserRoleEnum;
import com.closer.service.support.annotation.AuthCheck;
import com.closer.service.support.exception.BusinessException;
import com.closer.service.support.exception.ErrorCode;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import static com.closer.service.support.constant.UserConstant.USER_LOGIN_STATE;

@Aspect
@Component
public class AuthInterceptor {
    /**
     * 执行拦截
     *
     * @param joinPoint 切入点
     * @param authCheck 权限校验注解
     */
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        var mustRole = authCheck.mustRole();
        var requestAttributes = RequestContextHolder.currentRequestAttributes();
        var request = ((ServletRequestAttributes) requestAttributes).getRequest();
        // 当前登录用户
        var userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        var loginUser = (LoginUserVO) userObj;
        var mustRoleEnum = UserRoleEnum.getEnumByValue(mustRole);
        // 不需要权限，放行
        if (mustRoleEnum == null) {
            return joinPoint.proceed();
        }
        // 以下为：必须有该权限才通过
        // 获取当前用户具有的权限
        var userRoleEnum = UserRoleEnum.getEnumByValue(loginUser.getUserRole());
        // 没有权限，拒绝
        if (userRoleEnum == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 要求必须有管理员权限，但用户没有管理员权限，拒绝
        if (UserRoleEnum.ADMIN.equals(mustRoleEnum) && !UserRoleEnum.ADMIN.equals(userRoleEnum)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 通过权限校验，放行
        return joinPoint.proceed();
    }
}
